package com.example.casper.jnuexperiment2025;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class BookActivity extends AppCompatActivity {

    EditText editName, editPrice;
    Button buttonOK;
    int type;  // 0 添加，1 更新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_book);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        editName = findViewById(R.id.edittext_item_name);
        editPrice = findViewById(R.id.edittext_item_price);
        buttonOK = findViewById(R.id.button_item_details_ok);

        // ✅ 接收旧数据（用于更新）
        Intent intent = getIntent();
        type = intent.getIntExtra("type", 0);

        if (type == 1) { // 更新模式
            editName.setText(intent.getStringExtra("name"));
            editPrice.setText(String.valueOf(intent.getDoubleExtra("price", 0)));
        }

        // ✅ 点击确认返回
        buttonOK.setOnClickListener(v -> {

            String name = editName.getText().toString();
            String price = editPrice.getText().toString();

            // ✅ 校验输入不能为空
            if (name.isEmpty() || price.isEmpty()) {
                editName.setError("不能为空");
                editPrice.setError("不能为空");
                return;
            }

            Intent result = new Intent();
            result.putExtra("type", type);
            result.putExtra("name", name);
            result.putExtra("price", price);

            setResult(RESULT_OK, result);
            finish();
        });
    }
}
